#include "processor.hpp"

namespace libco {
    
static std::atomic<uint64_t> s_proc_id{1};
static std::atomic<uint64_t> s_proc_count{0};
constexpr static size_t LOCAL_QUEUE_LIMIT = 256;

/// 线程本地调度器
thread_local Processor *t_proc = nullptr;
thread_local uint64_t t_id;

Processor* Processor::GetThis() {
    LIBCO_ASSERT(t_proc != nullptr);
    return t_proc;
}

Processor::Processor() {
    LIBCO_LOG << "create processor id=" << s_proc_id;
    m_id = s_proc_id;
    ++s_proc_id;
    ++s_proc_count;
    m_local_tasks = new TaskQueue(LOCAL_QUEUE_LIMIT);
}

Processor::~Processor() {
    --s_proc_count;
    delete m_local_tasks;
    LIBCO_LOG_DEBUG << "delete processor id=" << m_id;
}

void Processor::add_task(Task task) {
    m_local_tasks->push(task);
}

void Processor::add_task(std::function<void()> task) {
    libco::Coroutine::ptr coroutine(new libco::Coroutine(task));
    m_local_tasks->push(coroutine);
}


size_t Processor::pop_task_n(std::vector<Task>& results, size_t n) {
    return m_local_tasks->try_pop_n(results, n);
}

size_t Processor::push_task_n(std::vector<Task>& results, size_t n) {
    return m_local_tasks->try_push_n(results, n);
}

size_t Processor::tasks() { 
    return m_local_tasks->tasks(); 
}

} // namespace libo
